declare var form: any;
declare var map: any;

/**
 * 定义地图图层加载服务
 */
export class LoadService {

    // 当前地图对象
    private curMap: any;
    // 树数据加载服务
    private ts: any;
    // 地图加载服务
    private ls: any;

    public layerData: any[] = [{}];
    public expandDataCache: any[] = [];
    public expandAll = true;

    constructor(curMap) {
        this.ts = new form.TreeService();
        this.curMap = curMap;
        this.ls = new map.LoadService(curMap);
    }

    /**
     * 加载配置信息
     */
    loadLayer() {
        form.DictionaryDataService.getDictionaryAll('p_gisyayerconfig',
            (data) => {
                // 三维没有加载过业务图层
                if (!form.ConfigService.is3DDataLoad) {
                    // 先清空
                    form.ConfigService.D3LayerData = [];
                }
                // 初始化展示的数据对象
                form.ConfigService.D2ShowLayers = [];
                this.oParent(data);
                this.oChecked(data);
                this.layerData = data;
                this.expandDataCache = this.ts.getExpandData(data, this.expandAll);
                // 地图初始化
                this.initLayer(this.layerData);
                // 三维已经加载业务图层
                form.ConfigService.is3DDataLoad = true;
                //
                if (form.ConfigService.loadLayerOver) {
                    form.ConfigService.loadLayerOver();
                }
            },
            (error) => { }
        );
    }

    // 处理数据的parent
    private oParent(data) {
        if (data && data.length > 0) {
            data.forEach(item => {
                this.oParentForChild(item);
            });
        }
    }

    private oParentForChild(data) {
        if (data.children && data.children.length > 0) {
            data.children.forEach(cItem => {
                cItem.parent = data;
                this.oParentForChild(cItem);
            });
        }
    }

    // 处理数据的checked和valid
    private oChecked(data) {
        if (data && data.length > 0) {
            data.forEach(item => {
                this.oCheckedItem(item);
                this.oCheckedForChild(item);
            });
        }
    }

    private oCheckedForChild(data) {
        if (data.children && data.children.length > 0) {
            data.children.forEach(cItem => {
                this.oCheckedItem(cItem);
                this.oCheckedForChild(cItem);
            });
        }
    }

    private oCheckedItem(item) {
        if (item.other.show === true && item.leaf) {
            item.checked = true;
        } else {
            item.checked = false;
        }
    }

    /***
     * 逆顺序初始化所有图层
     */
    private initLayer(datas: any[]): any {
        if (!(datas && datas.length)) {
            return;
        }

        // 如果地图没有初始化
        if (this.curMap.mapIsInited() === false) {
            return;
        }

        for (let i = datas.length - 1; i >= 0; i--) {
            const node = datas[i];
            this.initChildLayer(node);
            this.initNode(node);
        }
    }

    private initChildLayer(item) {
        if (item.children && item.children.length > 0) {
            for (let i = item.children.length - 1; i >= 0; i--) {
                const node = item.children[i];
                this.initChildLayer(node);
                this.initNode(node);
            }
        }
    }

    private initNode(node) {
        // 暂时设置只加载配置的geoserver tms服务,后续去掉
        if (node.other.dicType === '2') { // 类型为图层/
            const layer = {
                d2Layer: null,
                d3Layer: null
            };
            let id = '';
            // 解析大参数
            const param = JSON.parse(node.other.param);
            const mbParam = Object.assign({}, {}, param);

            // mapbox 数据 加载
            if (mbParam.mb) {
                if (mbParam.cs) {
                    delete mbParam.cs;
                }
                id = mbParam.mb.id;
                mbParam.mb.layout.visibility = node.other.show ? 'visible' : 'none';
                if (node.other.groupname) {
                    mbParam.mb.layerName = node.other.groupname;
                }
                const mblayer = this.ls.addLayer(node.other.type, node.other.layer_url, mbParam);
                layer.d2Layer = mblayer.d2Layer;
            }

            const csParam = Object.assign({}, {}, param);
            // mapbox 数据
            // 如果三维没有加载过数据
            if (csParam.cs) {
                // 如果之前3维加载过数据
                if (form.ConfigService.is3DDataLoad) {
                    if (form.ConfigService.D3LayerData.length > 0) {
                        const D3LayerData = form.ConfigService.D3LayerData;
                        for (let i = 0; i < D3LayerData.length; i++) {
                            const D3Layer = D3LayerData[i];
                            if (D3Layer.id === id) {
                                const d3Layer = D3Layer.d3Layer;
                                if (d3Layer && d3Layer.length > 0) {
                                    d3Layer.forEach(e => {
                                        e.removeLayer();
                                    });
                                }
                                D3LayerData.splice(i, 1);
                                break;
                            }
                        }
                    }
                }

                if (csParam.mb) {
                    delete csParam.mb;
                }
                csParam.cs.visible = node.other.show;
                if (node.other.groupname) {
                    csParam.cs.layers = node.other.groupname;
                }
                const cslayer = this.ls.addLayer('23', node.other.url, csParam);
                layer.d3Layer = cslayer.d3Layer;
                if (id !== '') {
                    // 先清空
                    form.ConfigService.D3LayerData.push({
                        id: id,
                        d3Layer: layer.d3Layer
                    });
                }
            }

            node.layer = layer;
            if (id !== '') {
                const showLayer = {
                    id: id,
                    node: node
                }
                // 二维图层加载列表
                form.ConfigService.D2ShowLayers.push(showLayer);
            }
        }
    }

    private updateLayer(node, checked) {
        if (node.other.dicType === '2' && node.layer) {
            // 更新图层显示状态
            node.other.show = checked;
            // 更新二维中的图层状态
            if (node.layer.d2Layer) {
                const d2Map = this.curMap.get2DMap();
                node.layer.d2Layer.forEach(e => {
                    // d2Map.setLayerVisible(e.id, checked);
                    if (this.curMap.get2DMapType() === 'mapboxgl') {
                        d2Map.setLayoutProperty(e.id, 'visibility', checked ? 'visible' : 'none');
                    }
                });

            }
            // 更新三维中的图层状态
            if (node.layer.d3Layer) {
                // let d3Map = this.curMap.get3DMap();
                node.layer.d3Layer.forEach(e => {
                    e.setVisible(checked);
                    // d3Map.show(e, checked);
                });
            }
        }
    }

    /**
     * 选择
     * @param item 项
     */
    select(item) {
        // 不是子节点，或者图层类型为图层目录时不能选择
        if (item.other.dicType === '1' || !item.leaf) {
            return;
        }

        if (item.checked && item.selected) {// 之前本身就是选中
            item.checked = false;
            this.checkChange(item, false);
            item.selected = false;
        } else if (item.checked && !item.selected) {// 只check没有select
            item.selected = true;
            this.ts.selecteEx(item, this.layerData);
        } else {
            item.checked = true;
            this.checkChange(item, true);
            item.selected = true;
            this.ts.selecteEx(item, this.layerData);
        }
    }

    /**
     * 选中
     * @param item 数据项
     */
    check(item) {
        if (item.checked) {
            if (item.selected) {
                item.selected = false;
            }
            this.checkChange(item, false);
        } else {
            if (item.selected) {
                item.selected = false;
            } else {
                this.ts.select(item, this.layerData);
            }
            this.checkChange(item, true);
        }
    }

    /**
     * 更新对象
     * @param checked 选中还是取消选中
     */
    checkChange(item, checked: boolean) {
        this.updateLayer(item, checked);
        // 执行图层选择改变对外事件
        if (form.ConfigService.LayerCheckChange) {
            form.ConfigService.LayerCheckChange(item, checked);
        }
    }

    /**
     * 展开
     * @param item 项
     */
    expand(item) {
        this.ts.expand(item);
    }
}
